import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/blueprint/user_print.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/control_room/user_room.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

part 'edit_profile_production.page.dart';

/// 编辑个人信息页面
@PagePath('/edit-profile')
class EditProfileProduction extends StatefulWidget {
  const EditProfileProduction({super.key});

  @pageRouteQuery
  static RouteQuery query() => const _$EditProfileProductionQuery().call();

  @override
  State<EditProfileProduction> createState() => _EditProfileProductionState();
}

class _EditProfileProductionState extends State<EditProfileProduction> {
  late TextEditingController _usernameController;
  late TextEditingController _signatureController;
  late UserRoom _userRoom;
  UserPrint? _currentUser;
  AssetEntity? _selectedAvatar;
  String? _localAvatarPath;
  DateTime? _selectedBirthday;

  @override
  void initState() {
    super.initState();
    _usernameController = TextEditingController();
    _signatureController = TextEditingController();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _userRoom = GlobalStateProvider.userRoomOf(context);
    _currentUser = _userRoom.fetchCurrentUser();

    if (_currentUser != null) {
      _usernameController.text = _currentUser!.username;
      _signatureController.text = _currentUser!.signature;
      // 保持当前用户头像为字符串形式，新选择的头像使用AssetEntity
      _selectedBirthday = _currentUser!.birthDate;
    }
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _signatureController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _generateHeader(context),

              // 内容区域 - 使用 Expanded 包裹 Column
              Expanded(
                child: Column(
                  children: [
                    // 头像
                    _generateAvatarSection(context),

                    40.h.heightBox,

                    // 编辑表单
                    _generateFormSection(context),

                    const Spacer(),
                  ],
                ),
              ),

              // 底部保存按钮
              _generateSaveButton(context),

              40.h.heightBox,
            ],
          ),
        ),
      ),
    );
  }

  /// 生成顶部导航栏
  Widget _generateHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.white.withValues(alpha: 0.5),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 36.sp,
              ),
            ),
          ),

          Expanded(
            child: Center(
              child: Text('Edit Information')
                  .fontSize(24.sp)
                  .textColor(ColorPalette.black)
                  .carterOne(weight: FontWeight.w400),
            ),
          ),
          36.w.widthBox,
        ],
      ),
    );
  }

  /// 生成头像部分
  Widget _generateAvatarSection(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        // 背景边框（avatar-border.png）
        SizedBox(
          width: 125.w,
          height: 125.w,
          child: Image.asset(AssetManifest.avatarBorder, fit: BoxFit.contain),
        ),
        // 头像（75.w * 75.w）和 + 按钮的容器
        Stack(
          clipBehavior: Clip.none,
          children: [
            Container(
              width: 75.w,
              height: 75.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: ColorPalette.white,
              ),
              child: ClipOval(
                child:
                    _localAvatarPath != null
                        ? Image.file(File(_localAvatarPath!), fit: BoxFit.cover)
                        : (_selectedAvatar != null
                            ? Image(
                              image: AssetEntityImageProvider(_selectedAvatar!),
                              fit: BoxFit.cover,
                            )
                            : (_currentUser?.avatar != null
                                ? Image.asset(
                                  _currentUser!.avatar,
                                  fit: BoxFit.cover,
                                )
                                : Icon(
                                  Icons.image_rounded,
                                  size: 40.sp,
                                  color: ColorPalette.iconGrey,
                                ))),
              ),
            ),
            // + 按钮 - 相对于头像容器的右下角
            Positioned(
              bottom: 0,
              right: 0,
              child: GestureDetector(
                onTap: () => _handlePickAvatar(context),
                child: Container(
                  width: 20.w,
                  height: 20.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: ColorPalette.blue1,
                  ),
                  child: Center(
                    child: Icon(
                      Icons.add_rounded,
                      color: ColorPalette.white,
                      size: 18.sp,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 生成表单部分
  Widget _generateFormSection(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        children: [
          // 用户名
          _generateTextField(
            label: 'Name',
            controller: _usernameController,
            hintText: 'Enter your name',
          ),

          24.h.heightBox,

          // 生日
          _generateBirthdayField(context),

          24.h.heightBox,

          // 签名
          _generateTextField(
            label: 'Personal Signature',
            controller: _signatureController,
            hintText: '*Enjoy The Present',
            maxLines: 3,
          ),
        ],
      ),
    );
  }

  /// 生成文本输入框
  Widget _generateTextField({
    required String label,
    required TextEditingController controller,
    required String hintText,
    int maxLines = 1,
  }) {
    // 根据 maxLines 决定高度：如果是 3 行则是 132.h，否则是 56.h
    final height = maxLines == 3 ? 132.h : 56.h;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label).fontSize(14.sp).textColor(ColorPalette.iconGrey).arimo(),
        8.h.heightBox,
        Container(
          height: height,
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: ColorPalette.white,
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: TextField(
            controller: controller,
            maxLines: maxLines,
            textInputAction: TextInputAction.done,
            style: TextStyle(fontSize: 16.sp, color: ColorPalette.black),
            decoration: InputDecoration(
              hintText: hintText,
              hintStyle: TextStyle(
                fontSize: 16.sp,
                color: ColorPalette.iconGrey.withValues(alpha: 0.5),
                fontStyle: FontStyle.italic,
              ),
              border: InputBorder.none,
            ),
          ),
        ),
      ],
    );
  }

  /// 生成生日输入框
  Widget _generateBirthdayField(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Birthday',
        ).fontSize(14.sp).textColor(ColorPalette.iconGrey).arimo(),
        8.h.heightBox,
        GestureDetector(
          onTap: () => _handlePickBirthday(context),
          child: Container(
            height: 56.h,
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            decoration: BoxDecoration(
              color: ColorPalette.white,
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: Row(
              children: [
                Text(
                  _selectedBirthday != null
                      ? '${_selectedBirthday!.year}-${_selectedBirthday!.month.toString().padLeft(2, '0')}-${_selectedBirthday!.day.toString().padLeft(2, '0')}'
                      : 'Select your birthday',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color:
                        _selectedBirthday != null
                            ? ColorPalette.black
                            : ColorPalette.iconGrey.withValues(alpha: 0.5),
                  ),
                ),
                const Spacer(),
                Icon(
                  Icons.chevron_right,
                  color: ColorPalette.black,
                  size: 20.sp,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 生成保存按钮
  Widget _generateSaveButton(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(vertical: 16.h),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [ColorPalette.blue2, ColorPalette.blue1],
          ),
          borderRadius: BorderRadius.circular(30.r),
        ),
        child: Text('Save', textAlign: TextAlign.center)
            .fontSize(20.sp)
            .textColor(ColorPalette.white)
            .arimo(weight: FontWeight.w700),
      ).withTapEffect(onTap: () => _handleSave(context)),
    );
  }

  /// 处理选择头像
  Future<void> _handlePickAvatar(BuildContext context) async {
    try {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          selectedAssets: [],
          requestType: RequestType.image,
        ),
      );

      if (result != null && result.isNotEmpty) {
        final asset = result.first;
        final file = await asset.file;

        if (file != null) {
          // 获取应用文档目录
          final appDir = await getApplicationDocumentsDirectory();
          final avatarDir = Directory('${appDir.path}/avatars');

          // 创建头像目录（如果不存在）
          if (!await avatarDir.exists()) {
            await avatarDir.create(recursive: true);
          }

          // 生成唯一文件名
          final fileName =
              'avatar_${DateTime.now().millisecondsSinceEpoch}${path.extension(file.path)}';
          final filePath = '${avatarDir.path}/$fileName';

          // 复制文件到本地目录
          await file.copy(filePath);

          setState(() {
            _selectedAvatar = asset;
            // 保存本地文件路径
            _localAvatarPath = filePath;
          });
          StageWhisper.cheer('Avatar selected successfully');
        }
      }
    } catch (e) {
      StageWhisper.lament('Failed to select avatar: $e');
    }
  }

  /// 处理选择生日
  Future<void> _handlePickBirthday(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedBirthday ?? DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime.now(),
    );

    if (picked != null) {
      setState(() {
        _selectedBirthday = picked;
      });
    }
  }

  /// 处理保存
  void _handleSave(BuildContext context) {
    if (_currentUser == null) return;

    final newUsername = _usernameController.text.trim();
    final newSignature = _signatureController.text.trim();

    // 验证用户名
    if (newUsername.isEmpty) {
      StageWhisper.caution('Please enter your name');
      return;
    }

    // 验证生日
    if (_selectedBirthday == null) {
      StageWhisper.caution('Please select your birthday');
      return;
    }

    // 更新用户信息
    final updatedUser = _currentUser!.copyWith(
      username: newUsername,
      signature: newSignature,
      birthDate: _selectedBirthday!,
      avatar: _localAvatarPath ?? _currentUser!.avatar,
    );

    final success = _userRoom.updateUserInfo(updatedUser);

    if (success) {
      StageWhisper.cheer('Profile updated successfully!');
      Navigator.of(context).pop();
    } else {
      StageWhisper.lament('Failed to update profile');
    }
  }
}
